package com.purchase.order.service.Impl;

import com.purchase.common.utils.uuid.IdUtils;
import com.purchase.manage.damian.OrderList;
import com.purchase.manage.damian.Supplier;
import com.purchase.manage.mapper.ManageSupplierMapper;
import com.purchase.order.domain.DAO.EvaluateDTO;
import com.purchase.order.domain.OrderEvaluate;
import com.purchase.order.mapper.EvaluateMapper;
import com.purchase.order.mapper.OrderMapper;
import com.purchase.order.service.IEvaluateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.rmi.ServerException;
import java.util.List;

/**
 * @author oyi46
 * @version 1.0
 * Create by 2023/7/11 14:34
 */

@Service
public class EvaluateServiceImpl implements IEvaluateService {

    @Autowired
    EvaluateMapper evaluateMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    ManageSupplierMapper supplierMapper;

    //查看未送达货 的订单
    @Override
    public List<OrderList> selectOrderList(OrderEvaluate evaluate) {
        return evaluateMapper.selectOrderList(evaluate);
    }

    //填写评价表
    @Override
    public OrderEvaluate insertEvaluate(OrderEvaluate evaluate) throws ServerException {
        OrderList orderList = orderMapper.selectOrder(evaluate.getOrderId());
//        if ( !"3".equals(orderList.getState())) {
//            throw new SecurityException("评价表填写失败");
//        }
        if(evaluateMapper.selectCount(orderList.getOrderId(),evaluate.getEvaluateType()) !=0){
            throw new ServerException("已填完第三方评价单");
        }
        Supplier supplier = supplierMapper.selectSupplierById(orderList.getSupplierId());
        if (supplier == null){
            throw new SecurityException("该供应商不存在，请联系管理员");
        }
        evaluate.setEvaluateId(IdUtils.randomSnowflake());
        evaluate.setCorporateName(supplier.getCorporateName());
        evaluate.setCompanyType(supplier.getType());
        evaluate.setOrderName(orderList.getOrderName());
        BigDecimal score = supplier.getScore().add(evaluate.getAverageScore());
        score = score.divide(BigDecimal.valueOf(2), 2, BigDecimal.ROUND_HALF_UP);
        supplierMapper.updateScore(orderList.getSupplierId(),score);
        supplierMapper.updateState(evaluate.getOrderId());
        if (evaluateMapper.insertEvaluate(evaluate) != 1) {
            throw new SecurityException("评价表填写失败");
        }
        return evaluate;
    }

    //查看所有评价表
    @Override
    public List<EvaluateDTO> selectList(OrderEvaluate evaluate) {
        return evaluateMapper.selectList(evaluate);
    }
}
